#!/bin/bash
# scripts/service.sh - 服务管理脚本

set -e

SERVICE_NAME="jfastfiler"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
INSTALL_DIR="/opt/jfastfiler"
CONFIG_FILE="${INSTALL_DIR}/config/config.yaml"

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }

# 显示使用说明
usage() {
    echo "使用方法: $0 {start|stop|restart|status|logs|enable|disable|update}"
    echo ""
    echo "命令说明:"
    echo "  start    - 启动服务"
    echo "  stop     - 停止服务"
    echo "  restart  - 重启服务"
    echo "  status   - 查看服务状态"
    echo "  logs     - 查看服务日志"
    echo "  enable   - 启用开机自启"
    echo "  disable  - 禁用开机自启"
    echo "  update   - 更新应用程序"
    echo ""
}

# 检查服务文件是否存在
check_service_file() {
    if [ ! -f "$SERVICE_FILE" ]; then
        log_error "服务文件不存在: $SERVICE_FILE"
        log_error "请先运行部署脚本: sudo ./deploy.sh"
        exit 1
    fi
}

# 检查是否以root运行
check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用sudo运行此命令"
        exit 1
    fi
}

# 启动服务
start_service() {
    check_root
    check_service_file
    
    log_info "启动 $SERVICE_NAME 服务..."
    systemctl start "$SERVICE_NAME"
    
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        log_success "服务启动成功"
    else
        log_error "服务启动失败"
        systemctl status "$SERVICE_NAME"
        exit 1
    fi
}

# 停止服务
stop_service() {
    check_root
    check_service_file
    
    log_info "停止 $SERVICE_NAME 服务..."
    systemctl stop "$SERVICE_NAME"
    
    if ! systemctl is-active --quiet "$SERVICE_NAME"; then
        log_success "服务已停止"
    else
        log_error "服务停止失败"
        exit 1
    fi
}

# 重启服务
restart_service() {
    check_root
    check_service_file
    
    log_info "重启 $SERVICE_NAME 服务..."
    systemctl restart "$SERVICE_NAME"
    
    sleep 2
    
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        log_success "服务重启成功"
    else
        log_error "服务重启失败"
        systemctl status "$SERVICE_NAME"
        exit 1
    fi
}

# 查看服务状态
status_service() {
    check_service_file
    
    log_info "$SERVICE_NAME 服务状态:"
    systemctl status "$SERVICE_NAME" --no-pager -l
}

# 查看服务日志
logs_service() {
    check_service_file
    
    local lines=${1:-50}
    
    log_info "显示最后 $lines 行日志:"
    journalctl -u "$SERVICE_NAME" -n "$lines" -f
}

# 启用开机自启
enable_service() {
    check_root
    check_service_file
    
    log_info "启用 $SERVICE_NAME 开机自启..."
    systemctl enable "$SERVICE_NAME"
    log_success "开机自启已启用"
}

# 禁用开机自启
disable_service() {
    check_root
    check_service_file
    
    log_info "禁用 $SERVICE_NAME 开机自启..."
    systemctl disable "$SERVICE_NAME"
    log_success "开机自启已禁用"
}

# 更新应用程序
update_service() {
    check_root
    
    log_info "开始更新 $SERVICE_NAME..."
    
    # 停止服务
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        log_info "停止运行中的服务..."
        systemctl stop "$SERVICE_NAME"
    fi
    
    # 备份当前版本
    local backup_dir="${INSTALL_DIR}/backups/$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$backup_dir"
    
    log_info "创建备份: $backup_dir"
    cp -r "${INSTALL_DIR}/bin" "${INSTALL_DIR}/config" "$backup_dir/" 2>/dev/null || true
    
    # 下载最新代码
    log_info "下载最新代码..."
    cd "$INSTALL_DIR"
    git pull origin main
    
    if [ $? -ne 0 ]; then
        log_error "代码更新失败"
        exit 1
    fi
    
    # 重新构建
    log_info "重新构建应用程序..."
    go build -o bin/jfastfiler cmd/server/main.go
    
    if [ $? -ne 0 ]; then
        log_error "构建失败，正在恢复备份..."
        cp -r "${backup_dir}/"* "${INSTALL_DIR}/"
        systemctl start "$SERVICE_NAME"
        exit 1
    fi
    
    chmod +x bin/jfastfiler
    
    # 启动服务
    log_info "启动更新后的服务..."
    systemctl start "$SERVICE_NAME"
    
    # 健康检查
    sleep 5
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        log_success "服务更新成功"
        log_info "备份保存在: $backup_dir"
    else
        log_error "服务启动失败，正在恢复备份..."
        cp -r "${backup_dir}/"* "${INSTALL_DIR}/"
        systemctl start "$SERVICE_NAME"
        exit 1
    fi
}

# 备份数据
backup_data() {
    check_root
    
    local backup_dir="${INSTALL_DIR}/backups/$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$backup_dir"
    
    log_info "创建数据备份: $backup_dir"
    
    # 停止服务
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        log_info "停止服务..."
        systemctl stop "$SERVICE_NAME"
    fi
    
    # 备份数据库和配置文件
    cp -r "${INSTALL_DIR}/data" "${INSTALL_DIR}/config" "$backup_dir/"
    
    # 重新启动服务
    log_info "启动服务..."
    systemctl start "$SERVICE_NAME"
    
    # 创建压缩包
    cd "${INSTALL_DIR}/backups"
    tar -czf "${backup_dir}.tar.gz" "$(basename "$backup_dir")"
    rm -rf "$backup_dir"
    
    log_success "备份完成: ${backup_dir}.tar.gz"
}

# 恢复数据
restore_data() {
    check_root
    
    local backup_file="$1"
    
    if [ -z "$backup_file" ]; then
        log_error "请指定备份文件路径"
        echo "可用备份:"
        find "${INSTALL_DIR}/backups" -name "*.tar.gz" -type f | sort -r
        exit 1
    fi
    
    if [ ! -f "$backup_file" ]; then
        log_error "备份文件不存在: $backup_file"
        exit 1
    fi
    
    log_info "从备份恢复: $backup_file"
    
    # 停止服务
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        log_info "停止服务..."
        systemctl stop "$SERVICE_NAME"
    fi
    
    # 解压备份
    local temp_dir=$(mktemp -d)
    tar -xzf "$backup_file" -C "$temp_dir"
    
    # 恢复数据
    local backup_name=$(basename "$backup_file" .tar.gz)
    local backup_path="$temp_dir/$backup_name"
    
    if [ -d "$backup_path/data" ]; then
        log_info "恢复数据库..."
        cp -r "$backup_path/data" "${INSTALL_DIR}/"
    fi
    
    if [ -d "$backup_path/config" ]; then
        log_info "恢复配置文件..."
        cp -r "$backup_path/config" "${INSTALL_DIR}/"
    fi
    
    # 清理临时文件
    rm -rf "$temp_dir"
    
    # 启动服务
    log_info "启动服务..."
    systemctl start "$SERVICE_NAME"
    
    log_success "数据恢复完成"
}

# 主函数
main() {
    case "$1" in
        start)
            start_service
            ;;
        stop)
            stop_service
            ;;
        restart)
            restart_service
            ;;
        status)
            status_service
            ;;
        logs)
            logs_service "$2"
            ;;
        enable)
            enable_service
            ;;
        disable)
            disable_service
            ;;
        update)
            update_service
            ;;
        backup)
            backup_data
            ;;
        restore)
            restore_data "$2"
            ;;
        *)
            usage
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"